package com.kitty.game.fixed.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.config.NPC;
import com.kitty.game.confirm.model.QuitFixedTeamConfirm;
import com.kitty.game.enter.RespGeneralNotify;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.fixed.entity.FixedTeam;
import com.kitty.game.fixed.message.*;
import com.kitty.game.role.model.GameObjectChar;
import com.kitty.game.role.model.Role;
import com.kitty.game.team.message.RespConfirm;
import com.kitty.game.team.model.Member;
import com.kitty.game.team.model.Team;
import com.kitty.game.team.service.TeamService;
import com.kitty.game.utils.NotifyModules;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.message.MessagePusher;
import com.kitty.common.utils.StaticParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.mina.core.session.IoSession;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class FixedTeamService {
    @Autowired
    Dao dao;
    @Autowired
    TeamService teamService;

    /**
     * 退出固定队
     * @param role
     * @param npc
     */
    public void quitFixedItem(Role role, NPC npc){
        //退出固定队
        if (StringUtils.isEmpty(role.getFixedTeam())) {
            sendNpcContent(role, npc, "施主你还没有结缔固定队呢？[离开]");
            return;
        }
        List<FixedTeam> fixedList = dao.query(FixedTeam.class, Cnd.where("uid", "=", role.getFixedTeam()));
        FixedTeam fixedTeam = new FixedTeam();
        if(fixedList.size()>0){
            fixedTeam = fixedList.get(0);
            String leader_uid = fixedTeam.getLeader_uid();
            String content = "";
            if(role.getRoleId() == Integer.parseInt(leader_uid)){
                content= String.format("施主，队长退出固定队后整个队伍会解散，确定吗？");
            }else{
                content = String.format("施主，是否确定退出固定队吗？");
            }
            role.setConfirm(new QuitFixedTeamConfirm());
            RespConfirm respConfirm = new RespConfirm();
            respConfirm.setTips(content);
            respConfirm.setConfirmText("确定");
            respConfirm.setCancelText("取消");
            MessagePusher.pushMessage(role, respConfirm);
        }

    }
    /**
     * 点击NPC 请求组成固定队菜单
     */
    public void requestItem(Role role, NPC npc){
        Team team = teamService.getTeam(role.getRoleId());
        if (team == null) {
            sendNpcContent(role, npc, "施主找谁结成固定队，请带他们来见贫僧好吗？[离开]");
            return ;
        }
        if (team.getList().size()<2) {
            sendNpcContent(role, npc, "施主找谁结成固定队，请带他们来见贫僧好吗？[离开]");
            return ;
        }
        //检查当前申请组固定队的人 。是不是有固定队， 如果有固定队，必须是之前固定队队长才可以邀请人加入
        if(StringUtils.isNotEmpty(role.getFixedTeam())){
            FixedTeamData fixedTeamData = new FixedTeamData();
            List<FixedTeam> fixedList = dao.query(FixedTeam.class, Cnd.where("uid", "=", role.getFixedTeam()));
            FixedTeam fixedTeam = new FixedTeam();
            if(fixedList.size()>0){
                fixedTeam = fixedList.get(0);
                String leader_uid = fixedTeam.getLeader_uid();
                if(Integer.parseInt(leader_uid) != role.getRoleId()){
                    sendMessage(role,"只有固定队长才可邀请人员加入固定队！");
                }
            }
        }
        //这里应该不判断队长， 这样 队长可以带别人来重新加入
        for (Member member : team.getList()) {
            if(!team.isLeader(member.getRoleId())){
                Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
                if(StringUtils.isNotEmpty(memberRole.getFixedTeam())){
                    sendMessage(role,"队伍中#Y"+memberRole.getName()+"#n已有固定队！");
                    return;
                    // sendNpcContent(role, npc, "施主您也有固定队[离开]");
                }
            }
        }
        Fixedteamstartdata fixedteamstartdata = new Fixedteamstartdata();
        MessagePusher.pushTeamMessage(role.getRoleId(), fixedteamstartdata);
    }
    // 确认固定队
    public void confirmFixedTeam(IoSession session, FixedTeamStartConfirm fixedTeamStartConfirm){
        //这里判断 申请固定队的人 是不是固定队队长，  固定队人满了没有。 固定队还能加几个人。  队伍中其他人是否可以加入
        Role role = SessionUtils.getRoleBySession(session);
        Team team = teamService.getTeam(role.getRoleId());
        if(team != null && team.getList().size()>= 2){
            if(!team.isLeader(role.getRoleId())){
                sendMessage(role,"只有队长才可操作！");
            }
            FixedTeamAppellation fixedTeamAppellation = new FixedTeamAppellation();
            fixedTeamAppellation.setType((byte)1);
            fixedTeamAppellation.setTeamName("");
            fixedTeamAppellation.setCostGold(0);
            MessagePusher.pushTeamMessage(role.getRoleId(), fixedTeamAppellation);

            //如果当前人的 固定队不为空的话  表示之前有固定队这次新增人员
            if(StringUtils.isNotEmpty(role.getFixedTeam())){
                FixedTeamData fixedTeamData = new FixedTeamData();
                List<FixedTeam> fixedList = dao.query(FixedTeam.class, Cnd.where("uid", "=", role.getFixedTeam()));
                FixedTeam fixedTeam = new FixedTeam();
                if(fixedList.size()>0){
                    fixedTeam = fixedList.get(0);
                    String leader_uid = fixedTeam.getLeader_uid();
                    if(Integer.parseInt(leader_uid) != role.getRoleId()){
                        sendMessage(role,"只有固定队长才可邀请人员加入固定队！");
                        return;
                    }
                    //取固定队现有人数
                    JSONArray parseArray = JSONObject.parseArray(fixedTeam.getMembers());
                    int fixedTeamOldNumber = parseArray.size();
                    //当前队伍人数 -1 + 固定队现有人数  超过5 就失败
                    int teamNumber = team.getList().size();
                    if(fixedTeamOldNumber + teamNumber >5){
                        sendMessage(role,"固定队超出人数限制，无法缔结");
                        return;
                    }
                    //如果 有固定队，并且通过校验，则直接跳过设置固定队名称页面。
                    Map<Integer, FixedTeamCheckData> fixedTeamMap = GameObjectChar.fixedTeamMap;
                    FixedTeamCheckData teamInfo = new FixedTeamCheckData();
                    teamInfo.setName(fixedTeam.getName());
                    fixedTeamMap.put(role.getRoleId(),teamInfo);

                    teamInfo.setAction((byte)1);
                    teamInfo.setName(fixedTeam.getName());
                    List<FixedTeamCheckData.FixedMember> memberList = new ArrayList<>();
                    //循环队伍中所有人员 添加到临时固定队信息中
                    for (Member member : team.getList()) {
                        Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
                        FixedTeamCheckData.FixedMember fixedMember = new FixedTeamCheckData.FixedMember();
                        fixedMember.setGid(memberRole.getRoleId()+"");
                        if(team.isLeader(member.getRoleId())) {
                            fixedMember.setHasConfirm((byte)1);
                        }else {
                            fixedMember.setHasConfirm((byte)0);
                        }
                        fixedMember.setIcon((int)memberRole.getRoleIcon());
                        fixedMember.setName(memberRole.getName());
                        memberList.add(fixedMember);
                    }
                    teamInfo.setMeberList(memberList);
                    MessagePusher.pushTeamMessage(role.getRoleId(), teamInfo);
                }
            }
        }
    }
    //设置固定队名称
    public void  setConfirmTeamName(IoSession session, SetFixedTeamAppllation setFixedTeamAppllation){
        String name = setFixedTeamAppllation.getName();
        Role role = SessionUtils.getRoleBySession(session);
        Team team = teamService.getTeam(role.getRoleId());
        Map<Integer, FixedTeamCheckData> fixedTeamMap = GameObjectChar.fixedTeamMap;
        FixedTeamCheckData fixedTeamCheckData = new FixedTeamCheckData();
        fixedTeamCheckData.setName(name);
        fixedTeamMap.put(role.getRoleId(),fixedTeamCheckData);

        if(team != null && team.getList().size()>= 2){
            if(!team.isLeader(role.getRoleId())){
                sendMessage(role,"只有队长才可操作！");
            }
            //只允许使用汉字
            char[] ch = name.toCharArray();
            for (char c : ch) {
                if (c < 0x4E00 || c > 0x9FA5) {
                    sendMessage(role,"队伍名称只允许输入汉字！");
                    return;
                }
            }
            if(name.length()<2 || name.length()>5) {
                sendMessage(role,"队伍名称只能在2-5字之间！");
                return;
            }
            FixedTeamAppellation fixedTeamAppellation = new FixedTeamAppellation();
            fixedTeamAppellation.setType((byte)1);
            fixedTeamAppellation.setTeamName(name);
            fixedTeamAppellation.setCostGold(0);
            MessagePusher.pushTeamMessage(role.getRoleId(), fixedTeamAppellation);
        }
    }
    //确认固定队名称
    public void confirmFixedTeamName(IoSession session, ConfirmFixedTeamAppllation confirmFixedTeamAppllation){
        Role role = SessionUtils.getRoleBySession(session);
        Team team = teamService.getTeam(role.getRoleId());
        Map<Integer, FixedTeamCheckData> fixedTeamMap = GameObjectChar.fixedTeamMap;
        if(!fixedTeamMap.containsKey(role.getRoleId())){
            sendMessage(role,"固定队出错！");
            return;
        }
        FixedTeamCheckData teamInfo = fixedTeamMap.get(role.getRoleId());
        String name =teamInfo.getName();
        if(team != null && team.getList().size()>= 2){
            if(!team.isLeader(role.getRoleId())){
                sendMessage(role,"只有队长才可操作！");
            }
            teamInfo.setAction((byte)1);
            teamInfo.setName(name);
            List<FixedTeamCheckData.FixedMember> memberList = new ArrayList<>();
            //循环队伍中所有人员 添加到临时固定队信息中
            for (Member member : team.getList()) {
                Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
                FixedTeamCheckData.FixedMember fixedMember = new FixedTeamCheckData.FixedMember();
                fixedMember.setGid(memberRole.getRoleId()+"");
                if(team.isLeader(member.getRoleId())) {
                    fixedMember.setHasConfirm((byte)1);
                }else {
                    fixedMember.setHasConfirm((byte)0);
                }
                fixedMember.setIcon((int)memberRole.getRoleIcon());
                fixedMember.setName(memberRole.getName());
                memberList.add(fixedMember);
            }
            teamInfo.setMeberList(memberList);
            MessagePusher.pushTeamMessage(role.getRoleId(), teamInfo);
        }
    }


    /**
     * 固定队结束页面
     * @param session
     * @param finishBuildFixedTeam
     */
    public void  finishTeamName(IoSession session, FinishBuildFixedTeam finishBuildFixedTeam){
        Role role = SessionUtils.getRoleBySession(session);
        int successNum = 0;
        Team team = teamService.getTeam(role.getRoleId());
        Map<Integer, FixedTeamCheckData> fixedTeamMap = GameObjectChar.fixedTeamMap;
        String uuid = StaticParam.getUUID();
        if(!fixedTeamMap.containsKey(team.getLeaderRoleId())){
            sendMessage(role,"固定队出错！");
            return;
        }
        //成员信息
        List<Map<String,Object>> infos = new ArrayList<>();
        FixedTeamCheckData teamInfo = fixedTeamMap.get(team.getLeaderRoleId());
        for (FixedTeamCheckData.FixedMember fixedMember : teamInfo.getMeberList()) {
            Map<String,Object> in = new HashMap<>();
            in.put("gid", fixedMember.getGid());
            in.put("joinTime",System.currentTimeMillis()/1000L);
            infos.add(in);
            if(role.getRoleId() == Integer.parseInt(fixedMember.getGid())){
                fixedMember.setHasConfirm((byte)1);
            }
            if(fixedMember.getHasConfirm() == 1){
                successNum++;
            }
        }

        if(successNum == team.getList().size()){
            //如果是最后一个人点击同意的话
            for (Member member : team.getList()) {
                Role teamRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
                FixedTeamFinishData fixedTeamFinishData = new FixedTeamFinishData();
                List<FixedTeamFinishData.FinishFixedMember> meberList = new ArrayList<>();
                for (FixedTeamCheckData.FixedMember fixedMember : teamInfo.getMeberList()) {
                    FixedTeamFinishData.FinishFixedMember finishFixedMember  = new FixedTeamFinishData.FinishFixedMember();
                    finishFixedMember.setGid(fixedMember.getGid());
                    finishFixedMember.setIcon(fixedMember.getIcon());
                    finishFixedMember.setName(fixedMember.getName());
                    meberList.add(finishFixedMember);
                }
                fixedTeamFinishData.setName(teamInfo.getName());
                fixedTeamFinishData.setMeberList(meberList);
                MessagePusher.pushMessage(teamRole, fixedTeamFinishData);
                MessagePusher.pushMessage(teamRole, new RespNotifyMiscEx("固定队伍缔结成功"));
            }
            //这里要判断 是否已经有固定队了。 如果有固定队 需要取出固定队信息 添加人员。、
            // 如果没有固定队， 创建固定队，加入所有人
            Role leaderRole = SpringUtils.getRoleService().getOnlinePlayer(team.getLeaderRoleId());
            if(StringUtils.isNotEmpty(leaderRole.getFixedTeam())){
                FixedTeamData fixedTeamData = new FixedTeamData();
                List<FixedTeam> fixedList = dao.query(FixedTeam.class, Cnd.where("uid", "=", leaderRole.getFixedTeam()));
                FixedTeam fixedTeam = new FixedTeam();
                if(fixedList.size()>0){
                    fixedTeam = fixedList.get(0);
                }
                JSONArray parseArray = JSONObject.parseArray(fixedTeam.getMembers());
                for(Map<String,Object> m:infos) {
                    //把新的成员添加进去,队长排除在外
                    if(!team.isLeader(Integer.parseInt(m.get("gid").toString()))) {
                        parseArray.add(m);
                    }
                }
                ////给队员设置固定队伍信息
                for (Member member : team.getList()) {
                    if(!team.isLeader(member.getRoleId())){
                        Role teamRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
                        //FixedTeamCheckData fixedTeamCheckData = teamRole.getExtendBox().getFixedTeamCheckData();
                        //teamRole.getExtendBox().setFixedTeamCheckData(teamInfo);
                        teamRole.setFixedTeam(fixedTeam.getUid());
                        teamRole.save();
                    }
                }
                fixedTeam.setMembers(parseArray.toJSONString());
                dao.insertOrUpdate(fixedTeam);
            }else{
                //这里给所有成员设置固定队信息
                for (Member member : team.getList()) {
                    Role teamRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
                    teamRole.setFixedTeam(uuid);
                    teamRole.save();
                }
                //固定队信息记录到数据库
                //固定信息记录到数据库
                FixedTeam fixedTeam = new FixedTeam();
                //队长
                fixedTeam.setLeader_uid(team.getLeaderRoleId()+"");
                fixedTeam.setAdd_time(new Date());
                fixedTeam.setLevel(8);
                fixedTeam.setName(teamInfo.getName());
                fixedTeam.setUid(uuid);
                fixedTeam.setMembers(JSONObject.toJSONString(infos));
                dao.insertOrUpdate(fixedTeam);
            }
            fixedTeamMap.remove(team.getLeaderRoleId());
        }else{
            //设置当前人为同意
            MessagePusher.pushMessage(role, teamInfo);
        }
    }

    /**
     * 取消固定队
     * @param session
     * @param finishBuildFixedTeam
     */
    public void  stopTeamName(IoSession session,  StopBuildFixedTeam stopBuildFixedTeam){
        log.info("取消缔结固定队伍");
        Role role = SessionUtils.getRoleBySession(session);
        Team team = teamService.getTeam(role.getRoleId());
        if(team != null){
            for (Member member : team.getList()) {
                Role teamRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
                if(member.getRoleId() != role.getRoleId()){
                    CancelBuildFixedTeam cancelBuildFixedTeam = new CancelBuildFixedTeam();
                    MessagePusher.pushMessage(teamRole, cancelBuildFixedTeam);
                    sendMessage(teamRole,"#Y"+role.getName()+"#n取消缔结固定队伍");
                }
            }
            sendMessage(role,"已取消缔结固定队伍!");
        }
        Map<Integer, FixedTeamCheckData> fixedTeamMap = GameObjectChar.fixedTeamMap;
        fixedTeamMap.remove(team.getLeaderRoleId());
    }

    /**
     * 查询固定队信息
     * @param session
     * @param reqFixedteamstartdata
     */
    public void  queryFixedTeam(IoSession session, ReqFixedteamstartdata reqFixedteamstartdata){
        Role role = SessionUtils.getRoleBySession(session);

        FixedTeamData fixedTeamData = new FixedTeamData();
        log.info("当前人："+role.getName()+" 固定队ID："+role.getFixedTeam());
        List<FixedTeam> fixedList = dao.query(FixedTeam.class, Cnd.where("uid", "=", role.getFixedTeam()));
        FixedTeam fixedTeam = new FixedTeam();
        if(fixedList.size()>0){
            fixedTeam = fixedList.get(0);
            fixedTeamData.setName(fixedTeam.getName());
            fixedTeamData.setLevel((byte)fixedTeam.getLevel());
            fixedTeamData.setIntimacy(fixedTeam.getIntimacy());
            fixedTeamData.setMaxIntimacy((fixedTeam.getLevel()+1)*1000);
            List<FixedTeamDataMembers> fixedTeamDataMembersList = new ArrayList<>();
            JSONArray parseArray = JSONObject.parseArray(fixedTeam.getMembers());
            for (int i = 0; i < parseArray.size(); i++) {
                JSONObject jsonObject = parseArray.getJSONObject(i);
                int roleId = Integer.parseInt(jsonObject.getString("gid"));
                FixedTeamDataMembers m = new FixedTeamDataMembers();
                Role teamRole = SpringUtils.getRoleService().getOnlinePlayer(roleId);
                m.setGid(roleId+"");
                if(teamRole != null) {
                    //在线状态
                    m.setName(teamRole.getName());
                    m.setLevel(teamRole.getLevel());
                    m.setIcon(teamRole.getRoleIcon());
                    m.setTao(teamRole.getTao());
                    m.setLastLogoutTime(0);
                    m.setJoinTime(jsonObject.getIntValue("joinTime"));
                }else {
                    teamRole = SpringUtils.getRoleService().getPlayerBy(roleId);
                    m.setName(teamRole.getName());
                    m.setLevel(teamRole.getLevel());
                    m.setIcon(teamRole.getRoleIcon());
                    m.setTao(0);
                    m.setLastLogoutTime((int) (new Date(teamRole.getEnterTime()).getTime()));
                    m.setJoinTime(jsonObject.getIntValue("joinTime"));
                }
                fixedTeamDataMembersList.add(m);
            }
            fixedTeamData.setFixedTeamDataMembersList(fixedTeamDataMembersList);
        }
        MessagePusher.pushMessage(role, fixedTeamData);

    }


    public void openDlg(Role role, String dlgName) {
        RespGeneralNotify respGeneralNotify = new RespGeneralNotify();
        respGeneralNotify.setNotify((short) NotifyModules.NOTIFY_OPEN_DLG); //打开对话框
        respGeneralNotify.setValue(dlgName);
        MessagePusher.pushMessage(role, respGeneralNotify);
    }

    public void sendNpcContent(Role role, NPC bossNpc, String content) {
        SpringUtils.getNpcService().sendNpcContent(role, bossNpc, content);
    }
    private void sendMessage(Role role ,String message){
        MessagePusher.pushMessage(role,new RespNotifyMiscEx(message));
    }
}
